<template>
	<view>
		<zero-loading type="circle" v-if="loading"></zero-loading>
		<view class="title "></view>
		
		<scroll-view scroll-y="true" class="scroll-Y" :style='{ height: scrollHeight }'>
			<view class="padding">
				<uni-collapse :accordion="true" @change="onTabChange">
					<uni-collapse-item  v-for="(item, index) in groups" :key="index" :title="item.group_name" :open="item.default" :show-animation="true" >
						
						<block v-for="(subItem, subIdx) in item.farms" :key="subIdx">
							<view class="item_panel margin-sm" hover-class="opcity" hover-stay-time="150" @tap="onFarmClick(subItem)">
								
								<view class="padding-sm flex align-center">
									<view class="flex-treble text-left">
										<text class="cuIcon-locationfill  text-blue "></text>
										<text
											class="text-farm text-md padding-left-xs">{{subItem.farmname}}</text>
								
									</view>
									<view class="flex-sub text-right" >
										<view v-if="subItem.detail.alarm_num>0" class="cu-tag round bg-red sm" @tap.stop="onFarmAlarm(subItem)">
											{{subItem.detail.alarm_num}}
										</view>
									</view>
								</view>
								
								<view class="  align-center text-center  border">
									<view class="flex padding-xs">
										<view class="flex-sub padding-xs split">
											<view class="">
												<view class="text-sm text-grey">昨日采食量达标率</view>
												<view class="margin-top-sm text-xl text-green">{{subItem.detail.health_per}} <text
														class="text-gray padding-left-xs text-xs">%</text></view>
											</view>
										</view>
										<view class="flex-sub padding-xs">
											<view class="">
												<view class="text-sm text-grey">在线/总设备</view>
												<view :class="subItem.detail.offline_num>0?'text-orange':'text-green'" class="margin-top-sm text-xl ">{{subItem.detail.online_num}}/{{subItem.detail.online_num+subItem.detail.offline_num}}</view>
											</view>
										</view>
									</view>
								
									
								</view>
								
								<view class="padding-xs">
									<view class="flex padding-bottom-sm padding-left-sm padding-right-sm">
										<view class=" cu-progress radius  active">
											<view :class="subItem.detail.health_per>95?'bg-green':'bg-orange'" class="" :style="[{ width: subItem.detail.health_per+'%' }]" >{{subItem.detail.health_per}}%</view>
										</view>
									</view>
								</view>
						
							</view>
						</block>
						
					</uni-collapse-item>
				</uni-collapse>
				
			</view>
		</scroll-view>
	</view>
</template>

<script>
	
	import * as api from 'common/api.js';
	const moment = require("../../../common/moment.min.js");
	import {
		API_HEAD
	} from '../../../common/api';
	export default {
		data() {
			return {
				loading:false,
				scrollHeight: 0,

				groups:[],
				groups_num:-1,
						
				title: '',
				farms_num:-1,
				farms:[],
				
				selectGroupIdx:-1,
			}
		},
		onReady() {
			// 计算scroll-view高度
			uni.getSystemInfo({
				success: resu => {
					//console.info("窗口高度:", resu.windowHeight)
					const query = uni.createSelectorQuery()
					query.select('.title').boundingClientRect()
					query.exec(res => {
		
						//console.info("顶部下拉区域:", res[0])
						this.scrollHeight = resu.windowHeight - res[0].height - 10 + 'px';
						//console.log('剩余高度', this.scrollHeight);
					})
				}
			})
		},
		onShow: function() {
			console.info("onShow")
			//console.log('selectGroupIdx：', this.selectGroupIdx);
			//this.onTabChange(this.selectGroupIdx)
			uni.preloadPage({url: "/pages/tabbar/home/home"});
			uni.preloadPage({url: "/pages/tabbar/my/my"});
			uni.setNavigationBarTitle({
				title: '集团场区列表'
			});
			this.checkPermission()
			//this.loadFarms()
			var that = this
			
			if(1==1)
			{
				that.loading = true
				that.loadGroups().then(function(res){
					that.loading = false
					if (res.code >= 0) {
				
						var list = res.data
						that.groups_num = list.length
						
						
						if(list.length>0){
							if(list.length==1){
								that.selectGroupIdx = 0
								list[0].default = true //默认展开
							}
							
							
							that.loading = true
							that.loadFarms().then(function(res1){
								that.loading = false
								if (res1.code >= 0) {
									var allFarms = res1.data
									//console.log(allFarms)
									for (var i = 0; i < allFarms.length; i++) {
										allFarms[i].detail = {
											"alarm_device_num": 0,
											"today_feed": 0,
											"today_water": 0,
											"yestoday_feed": 0,
											"yestoday_water": 0,
											"max_feed":0,
											"per":0,
											"health_per":0,
											"offline_num": 0,
											"online_num": 0,
											"num_stop": 0,
											"house_num": 0,
											"gw_num": 0,
											"gw_alive_num": 0,
										}
									
										//that.loadFarmInfo(allFarms[i].id)
									}
									
									for(var i=0;i<list.length;i++){
										var farms = []
										for(var x=0;x<allFarms.length;x++)
										{
											if(allFarms[x].group_name == list[i].group_name){
												farms.push(allFarms[x])
											}
										}
										//console.log(farms)
										list[i].farms = farms
									}
									
									//console.log(JSON.stringify(list))
									
									
									console.log('selectGroupIdx：', that.selectGroupIdx);
									that.onTabChange(that.selectGroupIdx)
								}
							})
						}
						
						that.groups = list
						
						console.info(that.groups)
						
					}
				})
			}
			
		},
		onLoad() {
			var is_admin = getApp().isAdmin()
			this.is_admin = is_admin
			console.log('is_admin=',this.is_admin)
		},
		methods: {
			checkPermission(){
				var that = this
				that.permission_edit = false
				that.permission_delete = false
				getApp().getActions("/Topo/Tree").then(function(res){
					if (res.code >= 0) {
						console.info(res.data)
						that.actions = res.data
						
						for(var i=0;i<that.actions.length;i++){
							if(that.actions[i].action_id=='edit'){
								that.permission_edit = true
							}
							if(that.actions[i].action_id=='delete'){
								that.permission_delete = true
							}
						}
					}else{
						uni.showToast({
							title: '系统异常，请联系管理员',
							icon: 'none'
						})
					}
				})
			},
			loadGroups() {
				var promise = new Promise(function(resolve, reject) {
					var token = getApp().getToken()
					api.myRequest({
						url: '/Api/Group',
						method: 'GET',
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'Authorization': 'Bearer ' + token + ''
						},
						data: {},
					}, false).then(res => {
						resolve(res);
					}).catch(err => {
						console.log(err)
						reject(err);
					})
				});
				return promise;
			},
			loadFarms() {
				var promise = new Promise(function(resolve, reject) {
					var token = getApp().getToken()
					api.myRequest({
						url: '/Api/Farm/List',
						method: 'GET',
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'Authorization': 'Bearer ' + token + ''
						},
						data: {},
					}, false).then(res => {
						resolve(res);
					}).catch(err => {
						console.log(err)
						reject(err);
					})
				});
				return promise;
			},
			loadFarmInfo(id) {
				var promise = new Promise(function(resolve, reject) {
					var token = getApp().getToken()
					api.myRequest({
						url: '/Api/Farm/SummaryInfo',
						method: 'GET',
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'Authorization': 'Bearer ' + token + ''
						},
						data: {
							id: id
						},
					}, false).then(res => {
						resolve(res);
					}).catch(err => {
						console.log(err)
						reject(err);
					})
				});
				return promise;
			},
			loadFarmHealth(id) {
				var promise = new Promise(function(resolve, reject) {
					var token = getApp().getToken()
					api.myRequest({
						url: '/Api/History/StatusHis',
						method: 'GET',
						header: {
							'content-type': 'application/x-www-form-urlencoded',
							'Authorization': 'Bearer ' + token + ''
						},
						data: {
							farmid: id,
							his_date:moment().add(-1, "days").format('YYYY-MM-DD'),
							online:'1',
							fields:'health'
						},
					}, false).then(res => {
						resolve(res);
					}).catch(err => {
						console.log(err)
						reject(err);
					})
				});
				return promise;
			},
			onFarmClick(item) {
				console.info(JSON.stringify(item))
				uni.navigateTo({
					url: "/pages/farm/farm?farmname=" + item.farmname + "&id=" + item.id
				})
			},
			onFarmAlarm(item) {
				console.info("onFarmAlarm",item)
				uni.navigateTo({
					url: "/pages/alarm/alarm?farmname=" + item.farmname + "&farmid=" + item.id
				})
			},
			
			onTabChange(idx){
				var that = this;
				if(idx!==''){
					that.selectGroupIdx = parseInt(idx);
				}else{
					that.selectGroupIdx = -1;
				}
				console.log('selectGroupIdx：', that.selectGroupIdx);
				if(that.selectGroupIdx<0){
					return;
				}
			
				for(var i=0;i<that.groups[that.selectGroupIdx].farms.length;i++){
					var id = that.groups[that.selectGroupIdx].farms[i].id;
					that.loadFarmInfo(id).then(function(res){
						
						if (res.code >= 0) {
							
							var farm_detail = res.data;
							console.log('farm_detail：',farm_detail)
							that.updateGroupFarmInfo(farm_detail)
							
							var farmid= farm_detail.farmid
							
							that.loadFarmHealth(farmid).then(function(res1){
								if (res1.code >= 0) {
									
									var data = res1.data;
									console.log('health_detail：',data)
									
									var good_num = 0;
									var high_num = 0;
									var low_num = 0;
									for(var i=0;i<data.length;i++){
										var item = data[i]
										if(item.online>0 && item.health && item.mode>0)
										if(item.health=="good"){
											good_num ++
										}else if(item.health=="high"){
											high_num ++
										}else if(item.health=="low"){
											low_num ++
										}
									}
									var total_num = good_num+high_num+low_num
									var health_detail = {id:farmid,total_num:total_num,good_num:good_num,high_num:high_num}
									that.updateGroupFarmHealth(health_detail)
								}
							});
						}
					});
					
				}
			},
			
			updateGroupFarmInfo(farm_detail){
				console.log("updateGroupFarmInfo")
				var that = this
				for(var i=0;i<that.groups[that.selectGroupIdx].farms.length;i++){
					var item = that.groups[that.selectGroupIdx].farms[i];
					var id = item.id
					
					if(farm_detail.farmid==id){
						item.detail = farm_detail
						//计算百分比
						if(item.detail.today_feed){
							item.detail.today_feed =parseFloat((item.detail.today_feed/1000).toFixed(3))
						}else{
							item.detail.today_feed = 0
						}
						
						if(item.detail.max_feed){
							item.detail.max_feed =parseFloat((item.detail.max_feed/1000).toFixed(3))
						}else{
							item.detail.max_feed = 0
						}
						if(item.detail.online_num){
						
						}else{
							item.detail.online_num = 0
						}
						if(item.detail.offline_num){
						
						}else{
							item.detail.offline_num = 0
						}
						
						//item.detail.per = parseFloat(parseFloat((item.detail.today_feed/item.detail.max_feed)*100).toFixed(1))
						
						item.detail.per = parseFloat(parseFloat((item.detail.online_num/(item.detail.offline_num+item.detail.online_num)*100).toFixed(1)))
						
						that.groups[that.selectGroupIdx].farms[i] = item
						
						console.log("updateGroupFarmInfo item",that.groups[that.selectGroupIdx].farms[i])
						break
					}
				}
				that.$forceUpdate()
			},
			
			updateGroupFarmHealth(health_detail){
				console.log("updateGroupFarmHealth")
				var that = this
				for(var i=0;i<that.groups[that.selectGroupIdx].farms.length;i++){
					var item = that.groups[that.selectGroupIdx].farms[i];
					var id = item.id
					
					if(health_detail.id==id){
						//计算百分比
						var health_per = 0
						if(health_detail.total_num==0){
							health_per = 0
						}else{
							health_per = parseFloat(parseFloat(((health_detail.good_num+health_detail.high_num)/(health_detail.total_num)*100).toFixed(1)))
						}
						
						
						that.groups[that.selectGroupIdx].farms[i].detail.health_per = health_per
						
						console.log("updateGroupFarmHealth item",that.groups[that.selectGroupIdx].farms[i])
						break
					}
				}
				that.$forceUpdate()
			},
		}
	}
</script>

<style>
	.bg-farm {
		min-height: 300rpx;
		border-radius: 10rpx;
		/* opacity: 0.9; */
		/* background: url("https://www.hozenn.com/iot/img/house.png") 80% 50% / 40% no-repeat linear-gradient(to top, rgba(255, 255, 255, 0.95)); */
		/* background-image:linear-gradient(to top, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0)),url('https://www.hozenn.com/iot/img/house.png'); */
		background-repeat: no-repeat;
		background-size: 20%;
		background-position: 55% 50%;
		background-color: rgba(100, 100, 100, 0.3);
	}
	.opcity{
		opacity: 0.6;
	}

	.padding-xxs {
		padding: 2px;
	}

	.title {
		position: relative;
		font-weight: 700;
		font-size: 24px;
		line-height: 44px;
		text-align: center;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		padding: 5rpx;
		/* background-color: tra; */
	}

	.split {
		border-right: 2px solid #f5f3f330;
	}
	
	.item_panel {
		min-height: 200rpx;
		border-radius: 5rpx;
		background-color: #ffffff;
		background-color: rgba(240, 240, 240, 0.6);
		/* box-shadow: 0px 2.5px 5px  rgba(100 100, 100, 0.9); */
		/* transform: translateY(-1px); */
		box-shadow: 0 4px 12px rgba(100, 100, 155, 0.3);
	}
</style>
